/**
 * 
 */
package org.istt.service.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.istt.dao.Dao;
import org.istt.service.Manager;
import org.istt.web.helper.ExtendedPaginatedList;

/**
 * @author Huy
 *
 */
public abstract class ManagerImpl<T, ID extends Serializable> implements Manager<T, ID> {
	protected Dao<T, ID> dao;

	@Override
	public List<T> getList() {
		return dao.findAll();
	}
	
	@SuppressWarnings("unchecked")
	protected Class<T> getPersistentClass() {
		return (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	@Override
	public ExtendedPaginatedList getList(ExtendedPaginatedList paginatedList) {
		List<T> results = dao.getAllRecordsPage(getPersistentClass(), paginatedList
                .getFirstRecordIndex(), paginatedList.getPageSize(), paginatedList
                .getSortDirection(), paginatedList.getSortCriterion());
			
        paginatedList.setList(results);
        paginatedList.setTotalNumberOfRows(dao.getAllRecordsCount(getPersistentClass()));
        
		return paginatedList;
	}

	@Override
	public T get(ID id) {
		return dao.findById(id, false);
	}

	@Override
	public void save(T t) {
		dao.makePersistent(t);
	}

	@Override
	public T insert(T t) {
		return dao.makePersistent(t);
	}

	@Override
	public void remove(ID id) {
		T t = dao.findById(id, false);
		dao.makeTransient(t);
	}

	@Override
	public List<T> search(T t, String... excludeProperty) {
		return dao.findSimilarTo(t, excludeProperty);
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.istt.service.Manager#isUnique(java.lang.String[], java.lang.String[], java.io.Serializable)
	 */
	@Override
	public boolean isUnique(String[] fields, String[] value, ID id) {
		return dao.isUnique(fields, value, id);
	};
}
